package com.hzit.provider.controller;

import com.hzit.api.bean.Dept;
import com.hzit.provider.service.DeptService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/dept")
public class DeptController {


    @Autowired
    private DeptService deptService;

    @GetMapping("/list")
    public List<Dept> list() {
        List<Dept> deptList = deptService.list();

        return deptList;
    }

    /**
     * @param dept
     * @return
     * @RequestBody:接受的参数 表示是一个json格式的数据
     */
    @PostMapping("/add")
    public boolean add(@RequestBody Dept dept) {
        return deptService.save(dept);
    }


    /**
     * @param id
     * @return
     * @HystrixCommand:如果当前函数出现异常，自动触犯指定方法nullDeptFallBack
     */
    @HystrixCommand(fallbackMethod = "nullDeptFallBack")
    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public Dept get(@PathVariable("id") Long id) {
        Dept dept = deptService.getById(id);

        if (dept == null) {
            throw new RuntimeException("部门信息为空！"); //制造异常
        }
        return dept;
    }

    /**
     * 自定义符合预期的方法
     *
     * @param id
     * @return
     */
    public Dept nullDeptFallBack(@PathVariable("id") Long id) {
        System.out.println("deptno...出现故障");
        return new Dept().setDeptno(500).setDname("没有找到部门ID:" + id + "相关的信息").setLoc("no loc 8004");
    }


}
